<?php
/**
 * Bdc Application level Controller
 *
 */
class BdcAppController extends AppController
{

    function beforeFilter($param_array = null)
    {
        parent::beforeFilter();
        //$PackageType = ClassRegistry::init('PackageType');
       // $pack_data = $PackageType->getByPackageId($this->global_company['package_id']);
       // $this->company_modules = $company_modules =  explode(',',$pack_data['PackageType']['modules']);

        //Validate for Crm and Management Module
        $request_controller = $this->request->params['controller'];
        //debug($request_controller);
        //debug($this->company_modules);
        if($request_controller == 'BdcOrders' || $request_controller == 'BdcManagement'){
            $needle = 'Crm';
            if($request_controller == 'BdcManagement'){
                $needle = 'Management';
            }
            $return = in_array($needle,$this->company_modules);
            if(!$return){//Your company is not permitted to access this module
                $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
            }
        }

        $user_type = $this->Auth->user('user_type');
        $user = $this->Auth->user('BdcUser');
        if ($user_type != 'bdc') {
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }

        if(in_array('Allow All',$param_array['bdc_user_types'])){

        }
        else{
            if(in_array($user['bdc_user_type'],$param_array['bdc_user_types'])){

            }
            else{
                $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
            }
        }
    }


    function getProductMonthlyConsolidate($bdc_id,$start_dt,$end_dt,$product_type_id=null,$omc=null)
    {
        $BdcDistribution = ClassRegistry::init('BdcDistribution');
        $conditions = array('BdcDistribution.bdc_id' => $bdc_id, 'BdcDistribution.record_type' => 'bdc', 'BdcDistribution.order_status' => 'Complete', 'BdcDistribution.deleted' => 'n','BdcDistribution.loading_date >=' => $start_dt, 'BdcDistribution.loading_date <=' => $end_dt);
        if($product_type_id){
            $conditions['BdcDistribution.product_type_id'] = $product_type_id;
        }
        if($omc){
            $conditions['BdcDistribution.omc_id'] = $omc;
        }
        $export_data = $BdcDistribution->find('all', array(
            'fields'=>array('BdcDistribution.id','BdcDistribution.loading_date','BdcDistribution.quantity','BdcDistribution.waybill_id','BdcDistribution.vehicle_no'),
            'conditions' => $conditions,
            'contain'=>array(
                'Omc'=>array('fields'=>array('Omc.id','Omc.name')),
                'BdcDepot'=>array('fields'=>array('BdcDepot.id','BdcDepot.name')),
                'ProductType'=>array('fields'=>array('ProductType.id','ProductType.short_name'))/*,
                'Region'=>array('fields'=>array('Region.id','Region.name')),
                'District'=>array('fields'=>array('District.id','District.name'))*/
            ),
            'order' => array("BdcDistribution.loading_date"=>'asc'),
            'recursive' => 1
        ));
        $gr = array();
        if($export_data){
            $needed_items = array();
            foreach ($export_data as $data) {
                $load_dt_arr = explode('-',$data['BdcDistribution']['loading_date']);
                $load_dt = $load_dt_arr[1].'/'.$load_dt_arr[0];
                $pro_id = $data['ProductType']['id'];
                $pro_name = $data['ProductType']['short_name'];
                $pro_qty = preg_replace('/,/','',$data['BdcDistribution']['quantity']);
                if(isset($needed_items[$pro_name])){}
                else{
                    $needed_items[$pro_name] = $pro_name;
                }
                if (isset($gr[$load_dt]) && isset($gr[$load_dt][$pro_id])) {
                    $gr[$load_dt][$pro_id]['qty'] = $gr[$load_dt][$pro_id]['qty'] + $pro_qty;
                } else { //New
                    $gr[$load_dt][$pro_id] = array(
                        'qty' => $pro_qty,
                        'name' => $pro_name
                    );
                }
            }
        }

        $gr_dt = array();
        foreach ($gr as $key => $value_arr) {
            $dow = array();
            ksort($value_arr);
            foreach ($value_arr as $key2 => $val) {
                $dow[$val['name']] = $val['qty'];
            }
            $gr_dt[$key] = $dow;
        }

        $days_arr = array();
        $products_arr1 = array();
        foreach ($gr_dt as $day => $data_arr) {
            $days_arr[] = $day;
            foreach ($data_arr as $name => $qty) {
                $products_arr1[$name][] = floatval($qty);
            }
        }
        //Arrange each product and it data
        $products_arr1 = array();
        foreach($days_arr as $day){
            foreach ($needed_items as $item) {
                if(isset($gr_dt[$day][$item])){
                    $products_arr1[$item]['data'][]= intval($gr_dt[$day][$item]);
                }
                else{
                    $products_arr1[$item]['data'][]= 0;
                }
            }
        }

        $products_arr = array();
        foreach ($products_arr1 as $pro => $qty_arr) {
            $products_arr[] = array(
                'name' => $pro,
                'data' => $qty_arr['data']
            );
        }

        //Prepare the table data headers
        $data_header = array();
        foreach($gr_dt as $dt=>$arr){
            foreach($arr as $id=>$val){
                $data_header[] = $id;
            }
        }
        $unig_arr = array_unique($data_header);
        sort($unig_arr);
        $t_head = array_merge(array('Date'),$unig_arr);
        //debug($t_head);
        $t_body_data = array();
        foreach($gr_dt as $dt=>$arr){
            $pr = array();
            foreach($t_head as $tkey => $tval){
                $pr[$tkey]='0';
            }
            $pr[0] = $dt;
            foreach($arr as $product_name=>$ltrs){
                $key = array_search($product_name,$t_head);
                $pr[$key]= $ltrs;
            }
            $t_body_data[] = $pr;
        }
        //debug($t_body_data);
        //Total the tbody data
        $tbody_totals = array();
        foreach($t_body_data as $dt){
            foreach($dt as $tbkey=>$tbval){
                if($tbkey == 0){
                    $tbody_totals[0] = '<strong>Total<strong/>';
                }
                else{
                    if(isset($tbody_totals[$tbkey])){
                        $tbody_totals[$tbkey] = intval($tbody_totals[$tbkey]) + intval($tbval);
                    }
                    else{
                        $tbody_totals[$tbkey] =  intval($tbval);
                    }
                }
            }
        }
        $t_body_data[] = $tbody_totals;

        return array(
            'x-axis' => $days_arr,
            'data' => $products_arr,
            'raw_data'=>$gr_dt,
            't_head'=>$t_head,
            't_body_data'=>$t_body_data
        );
    }


    function getMonthlyVariant($bdc_id,$month,$year,$query_filter,$product_type_id=null)
    {
        $year_month  = $year.'-'.$month;
        $BdcDistribution = ClassRegistry::init('BdcDistribution');
        $conditions = array('BdcDistribution.bdc_id' => $bdc_id, 'BdcDistribution.record_type' => 'bdc', 'BdcDistribution.order_status' => 'Complete', 'BdcDistribution.deleted' => 'n','BdcDistribution.loading_date  LIKE' => $year_month.'%');
        if($product_type_id){
            $conditions['BdcDistribution.product_type_id'] = $product_type_id;
        }
        $export_data = $BdcDistribution->find('all', array(
            'fields'=>array('BdcDistribution.id','BdcDistribution.loading_date','BdcDistribution.quantity','BdcDistribution.waybill_id','BdcDistribution.vehicle_no'),
            'conditions' => $conditions,
            'contain'=>array(
                'Omc'=>array('fields'=>array('Omc.id','Omc.name')),
                'BdcDepot'=>array('fields'=>array('BdcDepot.id','BdcDepot.name')),
                'ProductType'=>array('fields'=>array('ProductType.id','ProductType.short_name')),
                //'Region'=>array('fields'=>array('Region.id','Region.name')),
                //'District'=>array('fields'=>array('District.id','District.name'))
            ),
            //'order' => array("BdcDistribution.id"=>'desc'),
            'recursive' => 1
        ));
        $gr = array();
        if($export_data){
            foreach ($export_data as $data) {
                if($query_filter == 'Omc'){
                    $pro_id = $data['Omc']['id'];
                    $pro_name = $data['Omc']['name'];
                }
                elseif($query_filter == 'Depot'){
                    $pro_id = $data['BdcDepot']['id'];
                    $pro_name = $data['BdcDepot']['name'];
                }
                $pro_qty = intval(preg_replace('/,/','',$data['BdcDistribution']['quantity']));
                if (isset($gr[$pro_id])) {
                    $gr[$pro_id]['qty'] = $gr[$pro_id]['qty'] + $pro_qty;
                } else { //New
                    $gr[$pro_id] = array(
                        'qty' => $pro_qty,
                        'name' => $pro_name
                    );
                }
            }
        }

        $products_arr = array();
        foreach ($gr as $pro => $qty_arr) {
            $products_arr[] = array(
                $qty_arr['name'],
                $qty_arr['qty']
            );
        }
        $pie_data = $products_arr;
        $raw_pie = $pie_data;
        if ($pie_data) {
            $first_pie_data = $pie_data[0];
            $pie_data[0] = array(
                'name' => $first_pie_data[0],
                'y' => $first_pie_data[1],
                'sliced' => true,
                'selected' => true
            );
        }

        return array(
            'data' => $pie_data,
            'raw_data'=>$raw_pie
        );
    }


    function getMonthlyOmcVariant($bdc_id,$month,$year,$product_type_id=null)
    {
        return $this->getMonthlyVariant($bdc_id,$month,$year,'Omc',$product_type_id);
    }

    function getMonthlyDepotVariant($bdc_id,$month,$year,$product_type_id=null)
    {
        return $this->getMonthlyVariant($bdc_id,$month,$year,'Depot',$product_type_id);
    }


    function sendMessage($params){
        $all_users = $this->getMessageAddressList($params['bdc'],$params['omc'],$params['bdc_user_types'],$params['omc_user_types'],$params['excluded_users'],$params['message_origin']);
        $message['Message']=array(
            'title'=>$params['title'],
            'content'=>$params['content'],
            'user_id'=>$params['sender'],
            'msg_type'=>$params['msg_type']
        );
        return $this->send_message($message,$all_users);
    }


    function get_orders($start_dt,$end_dt,$group_by,$filter_omc){
        $company_profile = $this->global_company;
        return $this->getOrders('bdc',$company_profile['id'],$start_dt,$end_dt,$group_by,null,$filter_omc);
    }

    function admin_get_omc_list(){
        $company_profile = $this->global_company;
        $Omclist = $this->Omc->find('all', array(
            'conditions' => array('available' => 'Available','deleted' => 'n'),
            'recursive' => -1
        ));
        $omclist_arr = array();
        foreach ($Omclist as $value) {
            $omclist_arr[] = array('id'=>$value['Omc']['id'],'name'=>$value['Omc']['name']);
        }
        return $omclist_arr;
    }

    function get_omc_list(){
        $company_profile = $this->global_company;

        $condition_array = array(
            'Omc.available' => 'Available',
            'BdcOmc.bdc_id' => $company_profile['id'],
            'BdcOmc.deleted' => 'n'
        );
        $contain = array('Omc' => array('fields' => array('Omc.id', 'Omc.name')));
        $bdc_omcs = $this->BdcOmc->find('all', array(
            'fields' => array('BdcOmc.id', 'BdcOmc.omc_id'),
            'conditions' => $condition_array,
            'contain' => $contain,
            'recursive' => 1
        ));


        $omclists = array();
        foreach ($bdc_omcs as $value) {
            $omclists[] = $value['Omc'];
        }

        return $omclists;
    }

    function get_product_list(){
        $company_profile = $this->global_company;
        $products_type = $this->ProductType->find('all', array(
            'fields' => array('ProductType.id', 'ProductType.name'),
            'conditions' => array('ProductType.deleted' => 'n'),
            'recursive' => -1
        ));
        $products_lists = array();
        foreach ($products_type as $value) {
            $products_lists[] = $value['ProductType'];
        }

        return $products_lists;
    }

    function get_depot_list(){
        $company_profile = $this->global_company;
        $bdc_depots = $this->BdcDepot->find('all', array(
            'fields' => array('BdcDepot.id', 'BdcDepot.name','BdcDepot.short_name'),
            //'conditions' => array('BdcDepot.bdc_id' => $company_profile['id'], 'BdcDepot.deleted' => 'n'),
            'conditions' => array('BdcDepot.deleted' => 'n'),
            'recursive' => -1
        ));
        $bdc_depot_lists = array();
        foreach ($bdc_depots as $value) {
            //$bdc_depot_lists[] = $value['BdcDepot'];
            $bdc_depot_lists[] = array(
                'id'=>$value['BdcDepot']['id'],
                'name'=>$value['BdcDepot']['name'],
            );
        }

        return $bdc_depot_lists;
    }


}
